import { isNotEmpty, isEmpty, isNotUndefined } from '@/commons/utils';
import store from '@/store';
import request from '@/request';
import storage from '@/commons/storage';
import routes from './modules';
import { ZwMessage } from '@/commons';

let targetPath = '';

/**
 * 获取即将要跳转的路径
 * @param {*} menuList
 */
const getFirstPagePath = menuList => {
    if ((menuList || []).length === 0 || isNotEmpty(targetPath)) return;
    for (const item of menuList) {
        if (item.type !== 3 && item.list.length > 0) {
            getFirstPagePath(item.list);
        } else {
            targetPath = item.url;
            break;
        }
    }
};

/**
 * 根据用户点击的code获取菜单列表
 * @param {*} menuList
 * @param {*} code
 */
const getMenuList = (menuList, code) => {
    const menus =
        menuList.filter(item => {
            return item.code === code;
        })[0] || [];
    return menus;
};

/**
 * 设置数据状态并执行跳转
 * @param {*} zwauth
 * @param {*} code
 */
const jumpHander = (zwauth, code, callback) => {
    const useAuth = store.useAuthStore();
    useAuth.clear();
    useAuth.setAuth(zwauth, code);
    const tempMenus = getMenuList(zwauth.menuList, code);
    getFirstPagePath(tempMenus.list);
    callback(targetPath);
    targetPath = '';
};

/**
 * 用户点击模块跳转到对应模块
 * @param {*} item
 */
export const toPageHandler = (navAuth, code, callback, shopId) => {
    if (code === 'shopping_mall_mp') {
        if (isEmpty(shopId)) {
            shopId = navAuth.shopList[0]?.shopId;
        }
        if (isNotEmpty(shopId)) {
            request('queryNavByShopIdServ', { shopId }).then(res => {
                let shop = res.data.filter(item => item.shopId == shopId);
                const menus = shop[0]?.menuList[0];
                const idx = navAuth.menuList.findIndex(item => {
                    return item.code === code;
                });
                navAuth.menuList[idx] = menus;
                storage.set('ZW-AUTH', navAuth);
                storage.set('ZW-SHOPID', shopId);
                storage.set('ZW-SHOPNAME', shop[0]?.shopName);
                jumpHander(navAuth, code, callback);
            });
        } else {
            ZwMessage.error('无门店权限，请联系管理员');
        }
    } else {
        storage.set('ZW-AUTH', navAuth);
        jumpHander(navAuth, code, callback);
    }
};

/**
 * 查询目标路由是否存在权限里
 * @param {*} next
 * @param {*} path
 */
export const hasMenuPermission = (next, path) => {
    /**
     * 是否有门店id,如果没有就去找默认的第一个，如果有就用缓存的
     */
    let shopId = storage.get('ZW-SHOPID');
    const zwauth = storage.get('ZW-AUTH');

    /**
     * 查找路由是否存在权限菜单里
     * @param {*} auth
     * @returns
     */
    const checkAuthHanlder = auth => {
        const menuList = auth.menuList;
        const result = { hasPerm: false, code: '' };
        const idxs = [];
        const hasMenuPath = list => {
            for (const [index, menu] of list.entries()) {
                if (menu.type === 1) {
                    idxs.push(index);
                }
                if (menu.url === path) {
                    result.hasPerm = true;
                    result.code = menuList[idxs[idxs.length - 1]].code;
                    break;
                } else {
                    hasMenuPath(menu.list);
                }
            }
        };
        hasMenuPath(menuList);
        return result;
    };

    /**
     * 查找该路由是否是必要验证路由（路由表中meta属性有permAuth:false说明是非必要验证路由，可直接放过）
     * @returns
     */
    const checkPermAuthHandler = () => {
        const result = {};
        const ret = routes[0].children.filter(item => {
            if (item.path === path && isNotUndefined(item?.meta?.permAuth) && !item?.meta?.permAuth) {
                return item;
            }
        });
        if (ret.length > 0) {
            result.hasPerm = true;
            result.code = ret[0].meta.moduleCode;
        }
        return result;
    };

    /**
     * 路由回调函数
     * @param {*} auth
     */
    const callback = auth => {
        let result = checkPermAuthHandler();
        if (isEmpty(result)) {
            result = checkAuthHanlder(auth);
        }
        if (result.hasPerm) {
            const useAuth = store.useAuthStore();
            useAuth.setAuth(auth, result.code);
            next();
        } else {
            next('/404');
        }
    };

    if (isNotEmpty(shopId)) {
        callback(zwauth);
    } else {
        shopId = zwauth.shopList[0]?.shopId;
        const idx = zwauth.menuList.findIndex(item => {
            return item.code === 'shopping_mall_mp';
        });
        if (isNotEmpty(shopId)) {
            request('queryNavByShopIdServ', { shopId }).then(res => {
                const menus = res.data[0]?.menuList[0];
                zwauth.menuList[idx] = menus;
                storage.set('ZW-AUTH', zwauth);
                storage.set('ZW-SHOPID', shopId);
                storage.set('ZW-SHOPNAME', res.data[0]?.shopName);
                callback(zwauth);
            });
        } else {
            if (idx > 0) {
                zwauth.menuList.splice(idx, 1);
            }
            storage.set('ZW-AUTH', zwauth);
            callback(zwauth);
        }
    }
};
